package com.yuke.cloud.service.uac.security;

import com.google.common.collect.Sets;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;


/**
 * The class Security utils.
 *
 * @author
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class SecurityUtils {

	private static final String AUTH_LOGIN_AFTER_URL = "/user/loginAfter/**";
	private static final String AUTH_LOGOUT_URL = "/user/logout";

	/**
	 * Gets current login name.
	 *
	 * @return the current login name
	 */
	public static String getCurrentLoginName() {

		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {

			return ((UserDetails) principal).getUsername();

		}

		if (principal instanceof Principal) {

			return ((Principal) principal).getName();

		}

		return String.valueOf(principal);

	}

	public static Set<String> getCurrentAuthorityUrl() {
		Set<String> path = Sets.newHashSet();
		// mod by wg 20181221 权限会放在token的payload中，如果权限的过多，则会导致payload很长，因此改成获取角色方式,在UacPermissionServiceImpl中处理URL
//		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//		for (final GrantedAuthority authority : authorities) {
//			String url = authority.getAuthority();
//			if (StringUtils.isNotEmpty(url)) {
//				path.add(url);
//			}
//		}

		path.add(AUTH_LOGIN_AFTER_URL);
		path.add(AUTH_LOGOUT_URL);
		return path;
	}

	// add by wg 20181221
	public static List<Long> getCurrentAuthorityRoleIdList() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		List<Long> roleIdList = new ArrayList<>();
		for (final GrantedAuthority authority : authorities) {
			String roleId = authority.getAuthority();
//			log.info("=========roleId={}", roleId);
			if (StringUtils.isNotEmpty(roleId)) {
				if ("ROLE_ANONYMOUS".equalsIgnoreCase(roleId)) {  // 把ROLE_ANONYMOUS的roleId当成0处理
					roleIdList.add(0L);
				}else {
					roleIdList.add(Long.valueOf(roleId));
				}
			}
		}

//		log.info("=========roleIdList={}", roleIdList);
		return roleIdList;
	}
}
